package com.sayice.robotconflict.game.handler;

import com.alibaba.fastjson2.JSONObject;
import com.sayice.robotconflict.game.GameMatcher;
import com.sayice.robotconflict.game.msg.Message;
import com.sayice.robotconflict.game.msg.data.receive.MatchInfo;
import com.sayice.robotconflict.game.object.Player;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

/**
 * 匹配处理器
 *
 * @author shubing
 */
@Slf4j
public class MatchHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        Object[] playerAndMsg = (Object[]) msg;
        Player player = (Player) playerAndMsg[0];
        Message message = (Message) playerAndMsg[1];
        if ("match".equals(message.getType())) {
            switch (message.getAction()) {
                case "start":
                    if (player.state.get() != Player.State.IDLE) {
                        break;
                    }
                    MatchInfo matchInfo = ((JSONObject) message.getData()).to(MatchInfo.class);
                    String type = matchInfo.getType();
                    if ("single".equals(type)) {
                        GameMatcher.addMatch(player, matchInfo.getTeamSize());
                    } else if ("team".equals(type)) {
                    
                    }
                    break;
                default:
                    break;
            }
        } else {
            ctx.fireChannelRead(playerAndMsg);
        }
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        log.error("NettyHandler Exception from " + ctx.channel().remoteAddress(), cause);
        ctx.channel().close();
    }
}
